package filter;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthFilter implements Filter {

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String uri = request.getRequestURI();

        if (Urls.equals(uri)) {
            chain.doFilter(request, response);
            return;
        }


        String userName = (String) request.getSession().getAttribute("userName");
        if (null == userName) {
            System.out.printf("%s:用户未登录,AuthFilter进行拦截!\n",this.getClass().getSimpleName());
            response.sendRedirect("login.jsp");
            return;
        }

        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}

class Urls{
    static boolean equals(String uri) {
        ArrayList<String> allow= new ArrayList<String>();
        // 在这里加上放行名单
        allow.add("login");
        allow.add("login.jsp");
        allow.add("/");

        ArrayList<Boolean> result= new ArrayList<Boolean>();
        allow.forEach((e)->{
            result.add(uri.endsWith(e));
        });
        return result.contains(true);
    }
}